package cn.enjoy.socket.udp.multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;

/**
 * @author K
 * @date 2024-06-04 20:27
组播接收者B
 **/
public class UDPMulticastReceiveB {

    public static void main(String[] args) throws IOException {
        MulticastSocket multicastSocket = null;
        try {
            //创建组播接收者（这里绑定10086端口用来接收数据）
            multicastSocket = new MulticastSocket(10086);

            //将当前本机添加到224.0.0.1的这一组中（这样就可以接收到组发来的数据）
            InetAddress byName = InetAddress.getByName("224.0.0.1");
            multicastSocket.joinGroup(byName);

            //用来接收消息的包
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);

            //接收数据
            multicastSocket.receive(datagramPacket);

            //打印数据
            byte[] data = datagramPacket.getData();     // 获取组播数据
            int length = datagramPacket.getLength();    // 获取组播数据长度
            InetAddress address = datagramPacket.getAddress();  // 接收到哪个ip发来的组播数据
            int port = datagramPacket.getPort();    // 对方使用哪个端口发送的
            String str = new String(data, 0, length, StandardCharsets.UTF_8);
            System.out.println("接收B：接收组播数据:");
            System.out.println(str);
            System.out.println("从哪个ip发送来的组播数据：" + address + " 对方使用哪个端口发送数据：" + port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (multicastSocket != null) {
                //关闭
                multicastSocket.close();
            }
        }
    }
}